<?php

/**
 * @brief Klasa kontrolera offer
 *
 * Klasa udostepnia interfej CRUD ofert
 *
 *
 */
class OffersController extends Zend_Controller_Action
{
    protected $_user; /*!< Informacje zalogowanego uzytkownika. */
    protected $_mapper = null; /*!< Mapper ofert. */
    protected $request; /*!< Parametry zadania. */

    /**
     * @brief Metoda inicjujaca
     * 
     * Odpowiedzialan za szeg czynnosci:
     * - Odczyt informacji z flash messnegera
     * - Inicjacje maperow
     * - Odczyt statusu zalogowania
     * - Inicjacje kontekstu ajaxowego niektorych akcji
     */
    public function init()
    {
        /* Initialize action controller here */
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->messages = $this->_flashMessenger->getMessages();
        
        $this->_mapper = new Application_Model_OfferMapper;
        $this->request = $this->getRequest();
        $this->view->render('utility/_headbox.phtml');

        
        $auth = Zend_Auth::getInstance();
        if($auth->hasIdentity()){
            $this->_user = $auth->getIdentity();
        }
        
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('edit', 'json')
                ->addActionContext('show', 'html')
                ->addActionContext('show', 'json')
                ->addActionContext('new', 'html')
                ->initContext();
    }

    /**
     * @brief Akcja index
     * 
     * Akcja bez zastosowania - do ewentualnego
     * wykorzystania w przyszłosci
     */
    public function indexAction()
    {
        // action body
        
    }

    /**
     * @brief Akcja show
     * 
     * Akcja wyswietlajaca ofertę. W trakcie trwania aukcji uzytkownicy ktorzy
     * zglosili swoje oferty, beda mogli edytowac. Wewnatrz widokow (ajaxowego 
     * i normalnego) w takim wypadku pojawija sie odpowiednie odnosniki. 
     * 
     */
    public function showAction()
    {
        // action body
        $offer = $this->getOffer(FALSE);
        $this->view->offer = $offer;
        if($offer->offerOpen() && !empty($this->_user->login) &&
                $offer->getMarketEntity_id() == $this->_user->login){
            $this->view->editable = true;
        } else {
            $this->view->editable = false;
        }
            
    }
    
    /**
     * @brief Akcja mew
     * 
     * Akcja tworząca ofertę. zapisywane sa domyslne z gory ustalone wartosci
     * 
     */
    public function newAction()
    {
        $mapper = new Application_Model_OfferMapper();
        $newID;
        $this->view->id = 46;
        
        $offer = new Application_Model_Offer();
        $offer->setMinVolume(0);
        $offer->setMaxVolume(1);
        $offer->setOfferedPrice(0);
        $offer->setMarketEntity_id($this->_user->login);
        
        
        //pobierz parametry
        $auctionId = $this->request->getParam('auction');
        $groupId = $this->request->getParam('group');
        //brak grupy to nowa oferta nadrzedna
        if(empty($groupId)) { 
            //jak nie ma grupy to wywal wyjatek
            if(empty($auctionId)){
                throw new Exception('Niepoprawne parametry');
            } else {
                $offer->setFirstOffer(1);
                $offer->setAuction_id($auctionId);
                $newID = $mapper->save($offer);
            }
        } else {
            $offer->setFirstOffer(0);
            $groupMapper = new Application_Model_GroupMapper();
            $group = $groupMapper->find($groupId);
            $offer->setOwnerGroup_id($groupId);
            $offer->setHeadOffer_id($group->getHeadOffer_id());
            $headOfer = $mapper->find($group->getHeadOffer_id());
            $auctionId = $headOfer->getAuction_id();
            $offer->setAuction_id($auctionId);
            $newID = $mapper->save($offer);
        }
        //przekierowanei do grupy nadrzednej
        $this->_helper->redirector('edit', 'offers','default',array('id'=>$newID));
                
    }

    /**
     * @brief Akcja show
     * 
     * Akcja wyszukujaca oferty z wybranym toarem wewnatrz okreslonej aukcji
     * 
     */
    public function byCommodityAction()
    {
        // action body
        $auction = $this->request->getParam('auction');
        $commodity = $this->request->getParam('commodity');
        $offersMapper = new Application_Model_OfferMapper();
        $in = $offersMapper->fetchOfferByAuctionAndComponent($auction, $commodity, 1);
        $out = $offersMapper->fetchOfferByAuctionAndComponent($auction, $commodity, -1);
        $this->view->in = $in;
        $this->view->out = $out;
        $this->view->auction = $auction;
        $this->view->commodity = $commodity;
    }

    /**
     * @brief Akcja edit
     * 
     * Akcja edycji oferty. Rozne formularze sa wyswietlane dla oferty
     * nadrzednej i pod-ofert
     */
    public function editAction()
    {
        //parametry
        
        $error = Array();
        //wez oferte
        $offer = $this->getOffer(true);
        $auction_id = $offer->getAuction_id();
        $auctionMapper =  new Application_Model_AuctionMapper();
        $auction = $auctionMapper->find($auction_id);
        $startTime = new Zend_Date($auction->getStartTime());
        $endTime = new Zend_Date($auction->getEndTime());
        if($auction->getMarketEntity_id() != $this->_user->login &&
                empty($startTime)){
                if($endTime->isEarlier(Zend_Date::now()) || 
                        $startTime->isLater(Zend_Date::now())
                        ){
                  $this->_helper->flashMessenger->addMessage('error/Powiązana aukcja jest zamknięta!');
                  $this->_helper->redirector('details', 'auctions','default',array('id'=>$auction_id));
                }  
        }
        
        
        $form = new Application_Form_EditOffer(
                array('offerId'=>$offer->getOffer_id(),
                    'first' => $offer->getFirstOffer()));
        
        $groups = $offer->getCopyableGroups();
        //var_dump($groups);
        if(!empty($groups)) {
            $groupForm = new Application_Form_AddGroup(array(
                    'groups'=>$groups, 'offer' => $offer->getOffer_id()));
            $this->view->groupForm = $groupForm;
        }
        
         if($this->request->isPost()){
             $post = $this->request->getPost();
             if($form->isValid($post)){       
                 if(!empty($offer)){
                    //aktualizacja oferty
                    $offer->setOfferedPrice($post['offeredPrice']);
                    $offer->setMaxVolume($post['maxVolume']);
                    $this->_mapper->save($offer);
                 }     
             }
         }
        $this->view->usersComms = $this->fetchUserCommodities($auction_id);
        $this->view->actionsComms = $this->fetchAuctionCommodities($auction_id);
        $this->view->form = $form;
        $this->view->offer = $offer;
        $this->view->error = $error;
        //var_dump($offer);
    }
    
    /**
     * @brief Akcja delete
     * 
     * Akcja usuwajaca ofertę. usuniete moga byc tylko oferty bez towarow w 
     * wiazce
     * 
     */
    public function deleteAction() {
        $offer = $this->getOffer(true);
        //$offer = new Application_Model_Offer();
        
        $auction_id = $offer->getAuction_id();
        $head = $offer->getHeadOffer_id();
        $id = $offer->getOffer_id();
        
        $groups = $offer->getGroups();
        $components = $offer->getComponents();
        
        if($offer->offerOpen() &&
                empty($groups) &&
                empty($components)) {
        $this->_mapper->delete($id);
        $this->_helper->flashMessenger->addMessage('success/Usunięto oferte!');
            if($offer->getFirstOffer()) {
                $this->_helper->redirector('details', 'auctions','default',array('id'=>$auction_id));
            } else {
                $this->_helper->redirector('show', 'offers','default',array('id'=>$head));
            }
        }
        $this->_helper->flashMessenger->addMessage('error/Nie można usunąć tej oferty!');
        $this->_helper->redirector('edit', 'offers','default',array('id'=>$id));
    }


    /**
     * @brief Metoda pomocnicza getOffer
     * 
     * Metoda wydobywa z bazy danych aukcje o id podanym w parametrach zadania
     * HTTP. Jeseli akcja wywolujaca metode naklada ograniczenia dostepu to tutaj
     * wszystko jest badane 
     * 
     */
    private function getOffer($protected) {
        
        $id = $this->request->getParam('id');
        if(empty($id))
            throw new Zend_Controller_Action_Exception('Niepoprawne Id oferty', 404);
        //wez oferte
        $offer = $this->_mapper->find($id);
        if(empty($offer) )
            throw new Zend_Controller_Action_Exception('Nie ma oferty o tym numerze', 404);
        //$offer = new Application_Model_Offer();
        
        if($protected) {
            //sprawdz czy oferta nalezy do uzytkownika
            if($offer->getMarketEntity_id() != $this->_user->login){
                if(empty($this->_user) ) {
                    $this->_helper->flashMessenger->addMessage("warning/Zaloguj się!");
                    $this->_helper->redirector('login','auth');
                }
                else {
                    $this->_helper->flashMessenger
                        ->addMessage('error/Nie możesz zmieniać cudzych ofert!');
                    $this->_helper->redirector('index');
                }
            }
        }
        
        return $offer;
    }
    
    /**
     * @brief Metoda wyszukujeaca towary uzytkownika
     * 
     * Metoda wyszukujeaca towary uzytkownika. Usuwane sa te towary ktore 
     * pojawily sie na liscie towarow wewnatrz zadanej aukcji 
     * 
     */
    private function fetchUserCommodities($auctionId)
    {
        $query = 'MarketEntity_id = "'.$this->_user->login.'" and used = 0';
        $mapper = new Application_Model_CommodityMapper();
        $commodities = $mapper->fetchAll($query);
        $affieMapper = new Application_Model_CommodityAffiliationMapper();
        $list = $affieMapper->fetchList($auctionId);
        $newCommodities = array();
        foreach ($commodities as $commodity) {
            $id = $commodity->getCommodity_id();
            if(!in_array($id, $list)) {
                $newCommodities[] = $commodity;
            }
        }
        return $newCommodities;
    }
    
    /**
     * @brief Metoda wyszukujeaca towary nalezace do aukcji
     * 
     * Metoda wyszukujeaca towary ktore zostaly dodane do aukcji przez 
     * uzytkownikow 
     * 
     */
    private function fetchAuctionCommodities($auctionId)
    {
        $mapper = new Application_Model_CommodityMapper();
        $commodities = $mapper->fetchByAuction($auctionId);
        return $commodities;
    }




}







